/**
 * 作者： liushun
 * 时间： 2020/5/17
 * 功能： 程序启动
 * **/

import express from 'express';
import chalk from 'chalk';
import config from './config';
import router from './routes';
import './mongodb/db.js';
import bodyParser from 'body-parser'
import socket from 'socket.io'
import mongoose from 'mongoose'
import Socket from './models/socket'
import Message from './models/message'
import loger from './util/log'
import moment from 'moment'
import './redis/redis'

moment.locale('zh-cn');

const app = express();


// 服务器提交的数据json化
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

//验证
router(app);

//声明静态资源地址
app.use(express.static('image'));

//声明静态资源地址
app.use(express.static('voice'));

//声明静态资源地址
app.use(express.static('public'));


app.set('showStackError', true)
mongoose.set('debug', true)


const server = app.listen(config.port, () => {
  console.log(
    chalk.green(`成功监听端口：${config.port}`)
  )
});

const io = socket(server);

global.io = io;


io.on('connect', (socket)=>{
  console.log("socket connect");

  socket.on('login',async (user, fn)=>{

    let userId = user.id
    let socketId = socket.id

    let socketModal = {
      socketId,
      userId
    }
    const socketRes = await Socket.findOne({userId});
    try{
      if(!socketRes){
        let socket = new Socket(socketModal);
        await socket.save();
      }else{
        await Socket.updateOne({userId},{socketId})
      }
    }catch(e){
      fn('连接服务器失败')
    }
    fn('连接服务器成功')
  })

  socket.on('message', async (message, fn) => {
    fn(message);
    const {fromName, fromId, avatar, toName, toId, type, text, roomId, duration} = message;


    const messageId = await Message.find({'roomId': roomId}).count()

    console.log(messageId)

    let mess = {
      username: fromName,
      userId: fromId,
      avatar,
      msg: text,
      type: type,
      roomId,
      messageId,
      duration
    }

    const messModal = await new Message(mess).save()

    const selfSockets = await Socket.findOne({userId: fromId});


    // console.log(selfSockets)
    io.to(selfSockets.socketId).emit('message', messModal);


    const friendSockets = await Socket.findOne({ userId: toId });

    io.to(friendSockets.socketId).emit('message', messModal);
  })

})


io.on('disconnect', (socket)=>{
  console.log("socket disconnect");
})
